﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Dynamic;
using System.Linq;

namespace _180FrameWork.Common
{
    public static class MyExcelHelper
    {
        #region 读取
        /// <summary>
        /// 读取EXCCEL
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static DataTable OleDbReadToTable(string FileName)
        {
            return OleDbReadToTable(FileName, "Sheet1");
        }

        /// <summary>
        /// 读取EXCEL
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="SheetName"></param>
        /// <returns></returns>
        public static DataTable OleDbReadToTable(string FileName, string SheetName)
        {
            try
            {

                //string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = " + FileName + ";Extended Properties=Excel 8.0"; //此连接只能操作xls文件
                string strCon = " Provider = Microsoft.Ace.OleDb.12.0 ; Data Source = " + FileName + ";Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'"; //此连接可以操作xls和xlsx文件,HDR=Yes表示第一行是列头,IMEX=1可避免数据类型不一致导致冲突

                OleDbConnection myConn = new OleDbConnection(strCon); //新建OleDbConnection 对象创建连接
                string strCom = " SELECT * FROM [" + SheetName + "$] ";//查询语句差准cxcle表中车数据 myConn.Open ( ) ;//打开连接
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
                DataSet myDataSet = new DataSet();
                myCommand.Fill(myDataSet, "[" + SheetName + "$]");
                myConn.Close();
                return myDataSet.Tables[0];
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }
        /// <summary>
        /// 读取EXCEL(带打开文件对话框)
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static DataTable OleDbReadToTableWithDialog(string FileName)
        {
            return OleDbReadToTableWithDialog(FileName, "Sheet1");
        }
        /// <summary>
        /// 读取EXCEL(带打开文件对话框)
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="SheetName"></param>
        /// <returns></returns>
        public static DataTable OleDbReadToTableWithDialog(string FileName, string SheetName)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.FileName = FileName;
            ofd.Filter = "EXCEL(*.xls,*.xlsx)|*.xls;*.xlsx";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                return OleDbReadToTable(ofd.FileName, SheetName);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 读取EXCCEL
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static DataTable NPOIReadToTable(string FileName)
        {
            return NPOIReadToTable(FileName, "Sheet1");
        }
        /// <summary>
        /// 读取EXCCEL
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="SheetName"></param>
        /// <returns></returns>
        public static DataTable NPOIReadToTable(string FileName, string SheetName)
        {
            ISheet sheet = null;
            DataTable data = new DataTable();
            int startRow = 0;
            try
            {
                IWorkbook workbook = null;
                var fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                if (FileName.IndexOf(".xlsx") > 0) // 2007版本
                    workbook = new XSSFWorkbook(fs);
                else if (FileName.IndexOf(".xls") > 0) // 2003版本
                    workbook = new HSSFWorkbook(fs);

                if (SheetName != null)
                {
                    sheet = workbook.GetSheet(SheetName);
                    if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                    {
                        sheet = workbook.GetSheetAt(0);
                    }
                }
                else
                {
                    sheet = workbook.GetSheetAt(0);
                }
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数

                    for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
                    {
                        ICell cell = firstRow.GetCell(i);
                        if (cell != null)
                        {
                            string cellValue = cell.StringCellValue;
                            if (cellValue != null)
                            {
                                DataColumn column = new DataColumn(cellValue);
                                data.Columns.Add(column);
                            }
                        }
                    }
                    startRow = sheet.FirstRowNum + 1;

                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startRow; i <= rowCount; ++i)
                    {
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null　　　　　　　

                        DataRow dataRow = data.NewRow();
                        for (int j = row.FirstCellNum; j < cellCount; ++j)
                        {
                            if (row.GetCell(j) != null) //同理，没有数据的单元格都默认是null
                                dataRow[j] = row.GetCell(j).ToString();
                        }
                        data.Rows.Add(dataRow);
                    }
                }

                return data;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception: " + ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 读取EXCEL(带打开文件对话框)
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static DataTable NPOIReadToTableWithDialog(string FileName)
        {
            return NPOIReadToTableWithDialog(FileName, "Sheet1");
        }
        /// <summary>
        /// 读取EXCEL(带打开文件对话框)
        /// </summary>
        /// <param name="FileName"></param>
        /// <param name="SheetName"></param>
        /// <returns></returns>
        public static DataTable NPOIReadToTableWithDialog(string FileName, string SheetName)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.FileName = FileName;
            ofd.Filter = "EXCEL(*.xls,*.xlsx)|*.xls;*.xlsx";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                return NPOIReadToTable(ofd.FileName, SheetName);
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region DataGridView导出
        /// <summary>
        /// 表格控件导出到csv格式excel
        /// </summary>
        /// <param name="dg"></param>
        public static void DataGridViewExportToCSV(DataGridView dg)
        {
            StringBuilder strCSV = new StringBuilder();
            foreach (DataGridViewColumn c in dg.Columns)
            {
                if (c.Visible)
                {
                    strCSV.Append(c.HeaderText + ",");
                }
            }
            strCSV.Append("\n");
            foreach (DataGridViewRow r in dg.Rows)
            {
                foreach (DataGridViewColumn c in dg.Columns)
                {
                    if (c.Visible)
                    {
                        string v = "";
                        if (r.Cells[c.Name].Value != null)
                        {
                            v = ReplaceSpecialChars(r.Cells[c.Name].FormattedValue.ToStr());
                        }
                        if (c.ValueType != null)
                        {
                            switch (c.ValueType.Name.ToLower())
                            {
                                case "string":
                                    //判断是否全部是数字
                                    if (Regex.IsMatch(v, "^[0-9]*$"))
                                        strCSV.Append(v + "\t,");
                                    else
                                        strCSV.Append(v + ",");
                                    break;
                                default:
                                    strCSV.Append(v + ",");
                                    break;
                            }
                        }
                        else
                        {
                            strCSV.Append(v + ",");
                        }
                    }
                }
                strCSV.Append("\n");
            }
            MyFileHelper.WriteWithDialog(DateTime.Now.ToString("yyyyMMddHHmm"), strCSV.ToString(), "CSV文件|*.csv", System.Text.Encoding.GetEncoding("gb2312"), false);
        }
        /// <summary>
        /// 表格控件导出到html格式excel
        /// </summary>
        /// <param name="dg"></param>
        public static void DataGridViewExportToHTML(DataGridView dg)
        {
            StringBuilder sb = new StringBuilder();

            sb.AppendLine("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">");
            sb.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
            //写出列名 
            sb.AppendLine("<tr style=\"font-weight: bold; white-space: nowrap;\">");

            foreach (DataGridViewColumn c in dg.Columns)
            {
                if (c.Visible)
                {
                    sb.AppendLine("<td>" + c.HeaderText + "</td>");
                }
            }
            sb.AppendLine("</tr>");
            foreach (DataGridViewRow r in dg.Rows)
            {
                sb.Append("<tr>");
                foreach (DataGridViewColumn c in dg.Columns)
                {
                    if (c.Visible)
                    {
                        string v = "";
                        if (r.Cells[c.Name].Value != null)
                        {
                            v = r.Cells[c.Name].FormattedValue.ToStr();
                        }
                        if (c.ValueType != null)
                        {
                            switch (c.ValueType.Name.ToLower())
                            {
                                case "string":
                                    //判断是否全部是数字
                                    if (Regex.IsMatch(v, "^[0-9]*$"))
                                        sb.Append("<td style=\"vnd.ms-excel.numberformat:@\">" + v + "</td>");
                                    else
                                        sb.Append("<td>" + v + "</td>");
                                    break;
                                default:
                                    sb.Append("<td>" + v + "</td>");
                                    break;
                            }
                        }
                        else
                        {
                            sb.Append("<td>" + v + "</td>");
                        }
                    }
                }
                sb.AppendLine("</tr>");
            }
            sb.AppendLine("</table>");
            MyFileHelper.WriteWithDialog(DateTime.Now.ToString("yyyyMMddHHmm"), sb.ToString(), "EXCEL文件|*.xls", System.Text.Encoding.GetEncoding("gb2312"), false);
        }
        /// <summary>
        /// 表格控件导出到excel
        /// </summary>
        /// <param name="dg"></param>
        public static void DataGridViewExportToXLS(DataGridView dg)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.FileName = DateTime.Now.ToString("yyyyMMddHHmmss");
            sfd.Filter = "EXCEL文件|*.xlsx";
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                IWorkbook workbook = new XSSFWorkbook();
                ISheet s = workbook.CreateSheet("Sheet1");
                //创建列头
                IRow cRow = s.CreateRow(0);
                int x = 0;
                foreach (DataGridViewColumn c in dg.Columns)
                {
                    if (c.Visible)
                    {
                        cRow.CreateCell(x).SetCellValue(c.HeaderText);
                        x++;
                    }
                }
                //创建表格数据
                int y = 0;
                foreach (DataGridViewRow r in dg.Rows)
                {
                    y++;
                    IRow dRow = s.CreateRow(y);
                    x = 0;
                    foreach (DataGridViewColumn c in dg.Columns)
                    {
                        if (c.Visible)
                        {
                            dRow.CreateCell(x).SetCellValue(r.Cells[c.Name].FormattedValue.ToStr());
                            x++;
                        }
                    }

                }

                FileStream sw = File.Create(sfd.FileName);
                workbook.Write(sw);
                sw.Close();
            }
        }

        #endregion

        #region DataTable导出

        public static MemoryStream DataTableExportToXLS(DataTable DT, string[] ColumnReNameList = null)
        {
            IWorkbook workbook = new XSSFWorkbook();
            //创建日期样式
            ICellStyle dateStyle = workbook.CreateCellStyle();
            IDataFormat dataFormateCustom = workbook.CreateDataFormat();
            dateStyle.DataFormat = dataFormateCustom.GetFormat("yyyy-MM-dd HH:mm:ss");
            //创建工作表
            ISheet s = workbook.CreateSheet("Sheet1");
            //创建列头
            IRow cRow = s.CreateRow(0);
            int x = 0;
            if (ColumnReNameList != null)
            {
                foreach (var c in ColumnReNameList)
                {
                    cRow.CreateCell(x).SetCellValue(c);
                    x++;
                }
            }
            else
            {
                foreach (DataColumn c in DT.Columns)
                {
                    cRow.CreateCell(x).SetCellValue(c.ColumnName);
                    x++;
                }
            }
            //创建表格数据
            int y = 0;
            foreach (DataRow r in DT.Rows)
            {
                y++;
                IRow dRow = s.CreateRow(y);
                x = 0;
                foreach (DataColumn c in DT.Columns)
                {
                    if (r[c] == DBNull.Value)
                    {

                    }
                    else
                    {
                        switch (c.DataType.Name.ToLower())
                        {
                            case "bool":
                            case "boolean":
                                dRow.CreateCell(x).SetCellValue(r[c].ToBool());
                                break;
                            case "datetime":
                                var cell = dRow.CreateCell(x);
                                cell.CellStyle = dateStyle;
                                cell.SetCellValue(r[c].ToDate());
                                break;
                            case "int":
                            case "int32":
                            case "int64":
                            case "float":
                            case "double":
                            case "decimal":
                                dRow.CreateCell(x).SetCellValue(r[c].ToDb());
                                break;
                            default:
                                dRow.CreateCell(x).SetCellValue(r[c].ToStr());
                                break;
                        }
                    }
                    x++;
                }

            }
            //写入流
            var ms = new NpoiMemoryStream();
            ms.AllowClose = false;
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.AllowClose = true;
            return ms;
        }

        #endregion

        #region dynamic导出

        private static void DynamicCreateSheet(IWorkbook workbook, ICellStyle dateStyle, string SheetName, IList<dynamic> DT, string[] ColumnReNameList = null)
        {
            //创建工作表
            ISheet s = workbook.CreateSheet(SheetName);
            //创建列头
            IRow cRow = s.CreateRow(0);
            int x = 0;
            if (ColumnReNameList != null)
            {
                foreach (var c in ColumnReNameList)
                {
                    cRow.CreateCell(x).SetCellValue(c);
                    x++;
                }
            }
            else
            {
                if (DT.Count > 0)
                {
                    foreach (var c in DT[0])
                    {
                        cRow.CreateCell(x).SetCellValue(c.Key);
                        x++;
                    }
                }
            }
            //创建表格数据
            int y = 0;
            foreach (IDictionary<string, object> r in DT)
            {
                y++;
                IRow dRow = s.CreateRow(y);
                x = 0;
                foreach (var c in r.Keys)
                {
                    if (r[c] == null)
                    {

                    }
                    else
                    {
                        switch (r[c].GetType().Name.ToLower())
                        {
                            case "bool":
                            case "boolean":
                                dRow.CreateCell(x).SetCellValue(r[c].ToBool());
                                break;
                            case "datetime":
                                var cell = dRow.CreateCell(x);
                                cell.CellStyle = dateStyle;
                                cell.SetCellValue(r[c].ToDate());
                                break;
                            case "int":
                            case "int32":
                            case "int64":
                            case "float":
                            case "double":
                            case "decimal":
                                dRow.CreateCell(x).SetCellValue(r[c].ToDb());
                                break;
                            default:
                                dRow.CreateCell(x).SetCellValue(r[c].ToStr());
                                break;
                        }
                    }
                    x++;
                }
            }
        }

        public static MemoryStream MultDynamicExportToXLS(IList<DynamicExportModel> SheetList)
        {

            IWorkbook workbook = new XSSFWorkbook();
            //创建日期样式
            ICellStyle dateStyle = workbook.CreateCellStyle();
            IDataFormat dataFormateCustom = workbook.CreateDataFormat();
            dateStyle.DataFormat = dataFormateCustom.GetFormat("yyyy-MM-dd HH:mm:ss");

            foreach (var sheet in SheetList)
            {
                //创建工作表
                DynamicCreateSheet(workbook, dateStyle, sheet.SheetName, sheet.DT, sheet.ColumnReNameList);
            }

            //写入流
            var ms = new NpoiMemoryStream();
            ms.AllowClose = false;
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.AllowClose = true;
            return ms;
        }

        public static MemoryStream DynamicExportToXLS(IList<dynamic> DT, string[] ColumnReNameList = null)
        {
            IWorkbook workbook = new XSSFWorkbook();
            //创建日期样式
            ICellStyle dateStyle = workbook.CreateCellStyle();
            IDataFormat dataFormateCustom = workbook.CreateDataFormat();
            dateStyle.DataFormat = dataFormateCustom.GetFormat("yyyy-MM-dd HH:mm:ss");
            //创建工作表
            DynamicCreateSheet(workbook, dateStyle, "Sheet1", DT, ColumnReNameList);
            //写入流
            var ms = new NpoiMemoryStream();
            ms.AllowClose = false;
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.AllowClose = true;
            return ms;
        }

        public static MemoryStream DynamicExportToCSV(IList<dynamic> DT, string[] ColumnReNameList = null)
        {
            StringBuilder strCSV = new StringBuilder();

            if (ColumnReNameList != null)
            {
                foreach (var c in ColumnReNameList)
                {
                    strCSV.Append(c + ",");
                }
            }
            else
            {
                if (DT.Count > 0)
                {
                    foreach (var c in DT[0])
                    {
                        strCSV.Append(c.Key + ",");
                    }
                }
            }
            strCSV.Append("\n");
            //创建表格数据
            foreach (IDictionary<string, object> r in DT)
            {
                foreach (var c in r.Keys)
                {
                    string v = "";
                    if (r[c] != null)
                    {
                        v = ReplaceSpecialChars(r[c].ToStr());

                        switch (r[c].GetType().Name.ToLower())
                        {
                            case "string":
                                //判断是否全部是数字
                                if (Regex.IsMatch(v, "^[0-9]*$"))
                                    strCSV.Append(v + "\t,");
                                else
                                    strCSV.Append(v + ",");
                                break;
                            default:
                                strCSV.Append(v + ",");
                                break;
                        }
                    }
                    else
                    {
                        strCSV.Append(v + ",");
                    }
                }
                strCSV.Append("\n");
            }
            //写入流
            var ms = new MemoryStream(System.Text.Encoding.Default.GetBytes(strCSV.ToString()));

            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            return ms;
        }

        #endregion

        #region 泛型导出

        private static void ObjectCreateSheet<T>(IWorkbook workbook, ICellStyle dateStyle, string SheetName, IList<T> DT, string[] ColumnReNameList = null)
        {
            Type entityType = typeof(T); //T泛型

            //创建工作表
            ISheet s = workbook.CreateSheet(SheetName);
            //创建列头
            IRow cRow = s.CreateRow(0);
            int x = 0;
            if (ColumnReNameList != null)
            {
                foreach (var c in ColumnReNameList)
                {
                    cRow.CreateCell(x).SetCellValue(c);
                    x++;
                }
            }
            else
            {
                if (DT.Count > 0)
                {
                    foreach (var proInfo in entityType.GetProperties())
                    {
                        cRow.CreateCell(x).SetCellValue(proInfo.Name);
                        x++;
                    }
                }
            }
            //创建表格数据
            int y = 0;
            foreach (T r in DT)
            {
                y++;
                IRow dRow = s.CreateRow(y);
                x = 0;
                foreach (var proInfo in entityType.GetProperties())
                {
                    var result = proInfo.GetValue(r,null);
                    if (result == null)
                    {

                    }
                    else
                    {
                        switch (proInfo.ReflectedType.Name.ToLower())
                        {
                            case "bool":
                            case "boolean":
                                dRow.CreateCell(x).SetCellValue(result.ToBool());
                                break;
                            case "datetime":
                                var cell = dRow.CreateCell(x);
                                cell.CellStyle = dateStyle;
                                cell.SetCellValue(result.ToDate());
                                break;
                            case "int":
                            case "int32":
                            case "int64":
                            case "float":
                            case "double":
                            case "decimal":
                                dRow.CreateCell(x).SetCellValue(result.ToDb());
                                break;
                            default:
                                dRow.CreateCell(x).SetCellValue(result.ToStr());
                                break;
                        }
                    }
                    x++;
                }
            }
        }

        public static MemoryStream ObjectExportToXLS<T>(IList<T> DT, string[] ColumnReNameList = null)
        {
            IWorkbook workbook = new XSSFWorkbook();
            //创建日期样式
            ICellStyle dateStyle = workbook.CreateCellStyle();
            IDataFormat dataFormateCustom = workbook.CreateDataFormat();
            dateStyle.DataFormat = dataFormateCustom.GetFormat("yyyy-MM-dd HH:mm:ss");
            //创建工作表
            ObjectCreateSheet(workbook, dateStyle, "Sheet1", DT, ColumnReNameList);
            //写入流
            var ms = new NpoiMemoryStream();
            ms.AllowClose = false;
            workbook.Write(ms);
            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);
            ms.AllowClose = true;
            return ms;
        }

        public static MemoryStream ObjectExportToCSV<T>(IList<T> DT, string[] ColumnReNameList = null)
        {
            Type entityType = typeof(T); //T泛型

            StringBuilder strCSV = new StringBuilder();

            if (ColumnReNameList != null)
            {
                foreach (var c in ColumnReNameList)
                {
                    strCSV.Append(c + ",");
                }
            }
            else
            {
                if (DT.Count > 0)
                {
                    foreach (var proInfo in entityType.GetProperties())
                    {
                        strCSV.Append(proInfo.Name + ",");
                    }
                }
            }
            strCSV.Append("\n");
            //创建表格数据
            foreach (T r in DT)
            {
                foreach (var proInfo in entityType.GetProperties())
                {
                    var result = proInfo.GetValue(r, null);
                    string v = "";
                    if (result != null)
                    {
                        v = ReplaceSpecialChars(result.ToStr());

                        switch (proInfo.ReflectedType.Name.ToLower())
                        {
                            case "string":
                                //判断是否全部是数字
                                if (Regex.IsMatch(v, "^[0-9]*$"))
                                    strCSV.Append(v + "\t,");
                                else
                                    strCSV.Append(v + ",");
                                break;
                            default:
                                strCSV.Append(v + ",");
                                break;
                        }
                    }
                    else
                    {
                        strCSV.Append(v + ",");
                    }
                }
                strCSV.Append("\n");
            }
            //写入流
            var ms = new MemoryStream(System.Text.Encoding.Default.GetBytes(strCSV.ToString()));

            ms.Flush();
            ms.Seek(0, SeekOrigin.Begin);

            return ms;
        }

        #endregion

        #region 辅助
        /// <summary>
        /// 替换特殊字符
        /// </summary>
        /// <param name="input">字符串</param>
        /// <returns></returns>
        public static string ReplaceSpecialChars(string input)
        {
            if (input == null) return "";
            input = input.Trim().Replace("\"", "\"\"");
            if (input.Contains(",") || input.Contains("\r") || input.Contains("\n"))
                input = "\"" + input + "\"";
            return input;
        }

        #endregion
    }

    public class DynamicExportModel
    {
        public string SheetName { get; set; }

        public string[] ColumnReNameList { get; set; }

        public IList<dynamic> DT
        {
            get
            {
                if (this._DT == null)
                {
                    this._DT = new List<dynamic>();
                }
                return this._DT;
            }
            set
            {
                this._DT = value;
            }
        }
        private IList<dynamic> _DT;

      
    }
}
